/*
 * @Description:
 * @Author: fhw
 * @Date: 2023-02-23 15:46:26
 */
import { DoType, getDoTypeTitle } from '@/interfaces'
import { errorTips, successTips } from '@/utils'
import { isTrue } from '@/utils/tools'
import { clone, equals, flatten } from 'ramda'
import { defineComponent, PropType, reactive, ref, watch } from 'vue'
import { MenuButtonState, columns } from '../../menu/uilts'
import { ColumnProps } from 'ant-design-vue/lib/table/interface'
import { RoleState } from '../uilts'
import { UserDataModule } from '@/store/modules/user'
import { FormConfig } from '@/components'
import { useDiff } from '@/hooks/usediff'
type Key = ColumnProps['key'];
const props = {
    visible: {
        type: Boolean as PropType<boolean>,
        required: true,
    },
    dataSource: {
        type: Object as PropType<RoleState>,
    },
} as const
export default defineComponent({
    props,
    name: 'CreateIndex',
    emits: ['cancel', 'search'],
    setup(props, { emit }) {
        const { lhs, diff } = useDiff<RoleState>(['rolename', 'description', 'status', 'menu'])
        const rules = {
            rolename: [{ required: true, message: '请输入角色名称', trigger: 'change' }],
            description: [{ required: true, message: '请输入描述', trigger: 'change' }],
            status: [{ required: true, message: '请选择启用状态', trigger: 'change' }],
        }
        const pageState = reactive({
            loading: false,
            type: DoType.create,
            formData: {} as RoleState,
            /** 菜单数据 */
            dataSource: [] as any[],
            /** 张开数据 */
            expandedKeys: [] as number[],
            /** 菜单选中ID */
            checkedKeys: [] as number[],
            /** 按钮数据 */
            menuButton: [] as MenuButtonState[],
            /** 按钮选择 */
            selectedRowKeys: [] as Key[],
        })
        getMeun()
        async function getMeun() {
            pageState.checkedKeys = []
            const { success, data } = await API.server.menu.getMenuTree.request()
            if (success) {
                pageState.dataSource = [
                    {
                        id: 0,
                        pid: 0,
                        name: '全部',
                        type: 1,
                        sort: 0,
                        is_use: 1,
                        is_navbar: 1,
                        children: data
                    }
                ]
                pageState.expandedKeys = [0]
            }
        }
        function onSelectChange(selectedRowKeys: Key[]) {
            console.log('selectedRowKeys changed: ', selectedRowKeys);
            pageState.selectedRowKeys = selectedRowKeys
        }

        function cancel() {
            pageState.type = DoType.create
            pageState.formData = {}
            pageState.loading = false
            emit('cancel')
        }
        async function submit() {
            const role_menu = getRoleMenu(pageState.dataSource[0])
            const func = equals(pageState.type, DoType.create) ? API.server.role.createRole.request : API.server.role.updateRole.request
            pageState.loading = true
            const param = {
                rolename: pageState.formData.rolename as string,
                description: pageState.formData.description as string,
                status: pageState.formData.status as "enabled" | "disabled",
                menu: role_menu,
                id: pageState.formData.id as number
            }
            const diffStr = diff(param)
            const { success, msg } = await func({
                ...param,
                diff: diffStr?.filter(Boolean)
            } as any)
            pageState.loading = false
            if (success) {
                successTips(`${getDoTypeTitle(pageState.type)}成功`)
                cancel()
                emit('search')
                UserDataModule.getRoleList()
                return
            }
            errorTips(msg)
        }
        function getRoleMenu(data: any) {
            const role_menu = [] as any[]
            data.children?.forEach((item: any) => {
                if (pageState.checkedKeys.includes(item.id)) {
                    const menuButtonId = item.menuButton.filter((item: { id: number }) => pageState.selectedRowKeys.includes(item.id)).map((item: { id: number }) => item.id)
                    role_menu.push({
                        menuId: item.id,
                        menuButtonId
                    })
                }
                if (item.children && item.children.length > 0) {
                    role_menu.push(...getRoleMenu(item))
                }
            })
            return role_menu
        }
        watch(
            () => [props.visible, pageState.dataSource],
            (visible) => {
                if (visible && isTrue(pageState.dataSource)) {
                    pageState.formData = clone(props.dataSource) ?? {}
                    pageState.type = isTrue(props.dataSource?.id) ? DoType.edit : DoType.create
                    pageState.checkedKeys = props.dataSource?.menu?.map((item: any) => item.menuId) as number[] ?? []
                    pageState.selectedRowKeys = flatten(props.dataSource?.menu?.map((item: any) => item.menuButtonId) ?? [])
                    lhs.value = clone(pageState.formData)
                }
            }
        )
        return () => (
            <div>
                <a-modal
                    title={`${getDoTypeTitle(pageState.type)}角色`}
                    visible={props.visible}
                    onCancel={cancel}
                    footer={null}
                    centered
                    confirmLoading={pageState.loading}
                    width="50%"
                >
                    <a-form
                        class="ant-advanced-search-form"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 14 }}
                        model={pageState.formData}
                        rules={rules}
                        onFinish={submit}
                    >
                        <a-row>
                            <a-col span={24}>
                                <a-form-item name="rolename" label="角色名称">
                                    <a-input v-model={[pageState.formData.rolename, 'value']} />
                                </a-form-item>
                            </a-col>
                            <a-col span={24}>
                                <a-form-item name="status" label="是否启用">
                                    <FormConfig
                                        prop="status"
                                        v-model={[pageState.formData.status, 'value']}
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col span={24}>
                                <a-form-item name="description" label="描述">
                                    <a-input v-model={[pageState.formData.description, 'value']} />
                                </a-form-item>
                            </a-col>
                            <a-col span={24}>
                                <a-row>
                                    <a-col span={8} style="padding-right: 10px">
                                        <a-card title="菜单列表" style="border-radius: 6px;height: 100%">
                                            <a-tree
                                                checkable
                                                tree-data={pageState.dataSource}
                                                v-models={[[pageState.expandedKeys, 'expandedKeys'], [pageState.checkedKeys, 'checkedKeys']]}
                                                replaceFields={{
                                                    children: 'children', title: 'name', key: 'id'
                                                }}
                                                onSelect={(data: number[], { selectedNodes }: any) => {
                                                    pageState.menuButton = clone(selectedNodes[0].props?.menuButton)
                                                    // pageState.type = DoType.edit
                                                }}
                                                onCheck={(data: number[], { checkedNodes }: any) => {
                                                    const selectedRowKeys = [] as number[]
                                                    checkedNodes.forEach((item: { props: { menuButton: any[] } }) => {
                                                        const data = item.props.menuButton?.map((item: { id: any }) => item.id) ?? []
                                                        selectedRowKeys.push(...data)
                                                    })
                                                    pageState.selectedRowKeys = clone(selectedRowKeys)
                                                }}
                                            >
                                            </a-tree>
                                        </a-card>
                                    </a-col>
                                    <a-col span={16}>
                                        <a-card title="按钮信息" style="border-radius: 6px;" >
                                            <a-table row-selection={{ selectedRowKeys: pageState.selectedRowKeys, onChange: onSelectChange }} rowKey="id" dataSource={pageState.menuButton ?? []} columns={columns} pagination={false}></a-table>
                                        </a-card>
                                    </a-col>
                                </a-row>
                            </a-col>
                        </a-row>
                        <div style={{ textAlign: 'center', marginTop: '10px' }}>
                            {[DoType.create, DoType.edit].includes(pageState.type) && (
                                <a-button type="primary" loading={pageState.loading} html-type="submit">
                                    提交
                                </a-button>
                            )}
                            <a-button onClick={cancel}>取消</a-button>
                        </div>
                    </a-form>
                </a-modal>
            </div>
        )
    },
})
